<?php

declare(strict_types=1);

namespace EthanZ\HyperfExt\Request;

use Hyperf\HttpServer\Router\Dispatched;
use Hyperf\Validation\Request\FormRequest;

abstract class BaseRequest extends FormRequest
{


    /**
     * 通用验证
     */
    const COMMON_RULES = [
        'id'   => 'digits_between:1,20',
        'time' => 'digits:10',
    ];


    /**
     * 必要验证
     */
    const MUST_RULES = [
        'page'     => 'digits_between:1,20',
        'pageSize' => 'gte:1|max:100',
    ];


    /**
     * 组装验证信息
     *
     * @return array
     */
    final public function rules(): array
    {
        // 获取path信息.
        $action = $this->request->getAttribute(Dispatched::class)->handler->callback;
        // 截取className和actionName.
        list($class, $currentScene) = explode('@', $action);

        $rules      = [];
        $sceneRules = $this->scenes[$currentScene] ?? [];
        if ($sceneRules) {
            foreach ($sceneRules as $k => $v) {
                $rule = $this->oldRule($k, $v);
                if (is_string($k)) {
                    $vArr     = is_array($v) ? $v : explode('|', $v);
                    $rule[$k] = array_merge($rule[$k], $vArr);
                }

                $rules = array_merge($rules, $rule);
            }
            $rules = array_merge($rules, self::MUST_RULES);
        }

        return $rules;
    }


    /**
     * 获取原始规则
     *
     * @param string|int $k
     * @param mixed      $v
     *
     * @return array
     */
    public function oldRule(string|int $k, mixed $v): array
    {
        $allRules = $this->allRules();
        $oldRule  = [];
        if (isset($allRules[$k])) {
            // 转换数组形式.
            $oldRule[$k] = is_array($allRules[$k]) ? $allRules[$k] : explode('|', $allRules[$k]);
        } elseif (isset($allRules[$v])) {
            $oldRule[$v] = is_array($allRules[$v]) ? $allRules[$v] : explode('|', $allRules[$v]);
        }

        return $oldRule;
    }


    abstract protected function allRules(): array;
}
